package other;

/**
 * Created by lyyn on 2022/7/22.
 */
public class MinSubArray_209 {
    public static void main(String[] args) {
        Solution_3 solution_3 = new Solution_3();
        int[] arr = new int[]{1,2,3,3,2,1,4};
        int minLen = solution_3.minSubArrayLen_2(4,arr);
        System.out.println(minLen);
    }
}
class Solution_3 {
    //暴力破解
    public int minSubArrayLen_1(int target, int[] nums) {
        int minArray = Integer.MAX_VALUE;
        int arrayLen = 0;
        int sum = 0;
        for (int i = 0; i < nums.length; i++) {
            arrayLen = 1;
            sum = nums[i];
            if(sum >= target){
                return arrayLen;
            }
            for (int j = i+1; j < nums.length; j++) {
                sum += nums[j];
                arrayLen += 1;
                if (sum >= target){
                    minArray = minArray > arrayLen ? arrayLen : minArray;
                    break;
                }
            }
        }
        return minArray == Integer.MAX_VALUE ? 0 : minArray;
    }
    //滑动窗口
    public int minSubArrayLen_2(int target, int[] nums) {
        int minLen = Integer.MAX_VALUE;
        int arrLen = 0;
        int sum = 0;
        int j = 0;
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
            arrLen++;
            while(sum >= target){
                minLen = Math.min(minLen,arrLen);
                sum = sum - nums[j++];
                arrLen--;
            }
        }
        return minLen == Integer.MAX_VALUE ? 0 : minLen;
    }
}